import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterTest {
    public static void main(String[] args) {

    }

    @Test
    public void testFileWriter1() {
        FileWriter fw = null;
        try {
            //如果文件不存在，则创建，如果存在，则覆盖
            File file = new File("writer.txt");
            //append参数控制是否追加写入
            fw = new FileWriter(file, true);
            //fw = new FileWriter(file);
            fw.write("hello");
            fw.write(" world");
            System.out.println("输出成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
@Test
    public void copyWrite() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            File file = new File("Reader.txt");
            File file1 = new File("copy.txt");
            fw = new FileWriter(file1);
            fr = new FileReader(file);
            int len;
            char[] buf = new char[10];
            while ((len = fr.read(buf)) != -1) {
                fw.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void copyWriteNew() {
        File file = new File("Reader.txt");
        File file1 = new File("copy.txt");
        // 使用 try-with-resources 自动管理资源
        try( FileWriter fw =  new FileWriter(file1);
            FileReader  fr = new FileReader(file);) {
            int len;
            char[] buf = new char[1024];
            while ((len = fr.read(buf)) != -1) {
                fw.write(buf, 0, len);
            }
            System.out.println("文件复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
